package com.ask.forMe.utils;

import java.util.Map;

public class SimilarityUtils {
    public static double calculateCosineSimilarity(Map<Long, Double> item1Ratings, Map<Long, Double> item2Ratings) {
        double numerator = 0.0;
        double denominator1 = 0.0;
        double denominator2 = 0.0;

        // 遍历 item1Ratings 的用户评分
        for (Long userId : item1Ratings.keySet()) {
            // 如果用户也对 item2 评分，则计算分子和分母部分
            if (item2Ratings.containsKey(userId)) {
                double rating1 = item1Ratings.get(userId);
                double rating2 = item2Ratings.get(userId);

                numerator += rating1 * rating2;
                denominator1 += rating1 * rating1;
                denominator2 += rating2 * rating2;
            }
        }

        // 如果分母为 0，则返回 0（避免除零错误）
        return denominator1 == 0 || denominator2 == 0 ? 0 : numerator / (Math.sqrt(denominator1) * Math.sqrt(denominator2));
    }

}